using NHibernate;
//------------------------------------------------------------------------------
// <copyright file="WebDataService.svc.cs" company="Microsoft">
//     Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;

namespace JuSolution.Web.ApiService
{
    public class AppDataService : DataService<JuCloudy.Data.Nhibernate.Service.AppDataContext>, IDisposable
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {
            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);
            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
            config.SetEntitySetAccessRule("*", EntitySetRights.All);

            config.DataServiceBehavior.AcceptCountRequests = true;
            config.DataServiceBehavior.AcceptProjectionRequests = true;
            config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;

            config.UseVerboseErrors = true;
        }

        ISession session;

        protected override JuCloudy.Data.Nhibernate.Service.AppDataContext CreateDataSource()
        {
            var factory = CreateSessionFactory();

            this.session = factory.OpenSession();
            this.session.FlushMode = FlushMode.Auto;

            return new JuCloudy.Data.Nhibernate.Service.AppDataContext(this.session);
        }

        private static ISessionFactory CreateSessionFactory()
        {
            var mCfg = new NHibernate.Cfg.Configuration().Configure(
               System.Web.HttpContext.Current.Server.MapPath(
                    System.Configuration.ConfigurationManager.AppSettings["AppToursimNhCfg"]
                    ));

            ISessionFactory SessionFactory = null;

            mCfg.AddClass(typeof(JuCloudy.Data.Entity.Service.SysStructure));
            mCfg.AddClass(typeof(JuCloudy.Data.Entity.Service.AppToursimProduct));
            mCfg.AddClass(typeof(JuCloudy.Data.Entity.Service.AppToursimItinerary));
            mCfg.AddClass(typeof(JuCloudy.Data.Entity.Service.AppToursimContent));
            SessionFactory = mCfg.BuildSessionFactory();
            return SessionFactory;
        }

        public void Dispose()
        {
            session.Dispose();
        }
    }
}
